<?php
require_once "../../includes/db_lib.php";
require_once "../../includes/media.php";

$trip_id = isset($_GET['trip_id']) ? $_GET['trip_id'] : '';

$date_delims = array(":", "-", " ");

function mediaCmp($m1, $m2){
	$t1 = $m1->time_captured();
	$t2 = $m2->time_captured();
	
	$delims = array(":", "-", " ");
	
	if($t1->year() < $t2->year()){
		return 1;
	} elseif($t1->year() > $t2->year()) {
		return -1;
	}
	if($t1->month() < $t2->month()){
		return 1;
	} elseif($t1->month() > $t2->month()) {
		return -1;
	}
	if($t1->day() < $t2->day()){
		return 1;
	} elseif($t1->day() > $t2->day()) {
		return -1;
	}
	
	//echo $t1->month();

	$t1 = $m1->time_captured()->value();
	$t2 = $m2->time_captured()->value();
	$t1 = str_replace($delims, '.', $t1);
	$t2 = str_replace($delims, '.', $t2);
	list($t1yr, $t1month, $t1day, $t1hr, $t1min, $t1sec) = split('\.', $t1);
	list($t2yr, $t2month, $t2day, $t2hr, $t2min, $t2sec) = split('\.', $t2);
	
	if($t1hr < $t2hr){
		return -1;
	} elseif($t1hr > $t2hr) {
		return 1;
	}
	if($t1min < $t2min){
		return -1;
	} elseif($t1min > $t2min) {
		return 1;
	}
	if($t1sec < $t2sec){
		return -1;
	} elseif($t1sec > $t2sec) {
		return 1;
	}
	return -1;

}

//Get an of all the relevant media here
$db_conn = new DBConn();
$query = "select * from media where trip_id = ".$trip_id." order by time_captured desc";
$result = $db_conn->query($query);


$media_arr = array();
$lats = array();
$lngs = array();
$dates = array();
$audios = array();
$orientations = array();


$i = 0;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    $m = new Media($row);
	$media_arr[$i] = $m;
	$i++;
}


usort($media_arr, "mediaCmp");

for($i = 0; $i < count($media_arr); $i++){
	$m = $media_arr[$i];
	$lats[$i] = $m->latitude();
	$lngs[$i] = $m->longitude();
	$dates[$i] = $m->time_captured()->value();
	$audios[$i] = $m->audio_filename();
	$orientations[$i] = $m->photo_orientation();
}

$months = array("01" => "January", "02" => "February", "03" => "March", "04" => "April", "05" => "May", "06" => "June", "07" => "July", "08" => "August", "09" => "September", "10" => "October", "11" => "November", "12" => "December",);

function differentDay($t1, $t2){
	if($t1->month() == $t2->month() && $t1->day() == $t2->day() && $t1->year() == $t2->year()){
		return false;
	}
	return true;
}



?>

<html>

	<head>
    	<link type="text/css" rel="stylesheet" href="travel.css"/>
    	
    	<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAAy2oS_ZMsQe_3mI5CCkgldhTkuwkKlU4s7cdblE9QRdlrziVB1hT4rErAEag1P1L0CPdAeA7PdRPb6w"
            type="text/javascript"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
		<script src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
		
		<!-- soundManager API -->
		<script src="soundmanager/script/soundmanager2.js"></script>
		
		<!-- Page player core CSS -->
		<link rel="stylesheet" type="text/css" href="soundmanager/demo/page-player/css/page-player.css" />

		<!-- soundManager.useFlashBlock: related CSS -->
		<link rel="stylesheet" type="text/css" href="soundmanager/demo/flashblock/flashblock.css" />

		<!-- optional: annotations/sub-tracks/notes, and alternate themes -->

		<link rel="stylesheet" type="text/css" href="soundmanager/demo/page-player/css/optional-annotations.css" />
		<link rel="stylesheet" type="text/css" href="soundmanager/demo/page-player/css/optional-themes.css" />
		
		
		<!-- mp3 button css and script -->
		
		<link rel="stylesheet" type="text/css" href="soundmanager/demo/mp3-player-button/css/mp3-player-button.css" />
		<script type="text/javascript" src="soundmanager/demo/mp3-player-button/script/mp3-player-button.js"></script>
		
		
		<style type="text/css">
			ul.playlist li .comment {font-size:0.65em;opacity:0.5}
		</style>



		<script>

			// demo only, but you can use these settings too..
			soundManager.flashVersion = 9;
			soundManager.useHighPerformance = true; // keep flash on screen, boost performance
			soundManager.wmode = 'transparent'; // transparent SWF, if possible
			soundManager.useFastPolling = true; // increased JS callback frequency
			soundManager.url = 'soundmanager/swf/';
			soundManager.debugMode = false;

			// custom page player configuration
			var PP_CONFIG = {
  				autoStart: false,      // begin playing first sound when page loads
  				playNext: false,        // stop after one sound, or play through list until end
  				useThrottling: false,  // try to rate-limit potentially-expensive calls (eg. dragging position around)</span>
  				usePeakData: true,     // [Flash 9 only] whether or not to show peak data (left/right channel values) - nor noticable on CPU
  				useWaveformData: false,// [Flash 9 only] show raw waveform data - WARNING: LIKELY VERY CPU-HEAVY
  				useEQData: false,      // [Flash 9 only] show EQ (frequency spectrum) data
  				useFavIcon: false,     // try to apply peakData to address bar (Firefox + Opera) - performance note: appears to make Firefox 3 do some temporary, heavy disk access/swapping/garbage collection at first(?) - may be too heavy on CPU
  				useMovieStar: true     // Flash 9.0r115+ only: Support for a subset of MPEG4 formats.
			}

		</script>
		
		<!-- Page player main script -->
		<script src="soundmanager/demo/page-player/script/page-player.js"></script>

		<!-- optional: Metadata UI prototype (not needed unless you want the bottom-most demo bits) -->
		<script src="soundmanager/demo/page-player/script/optional-page-player-metadata.js"></script>

		
    	<script type="text/javascript">
    		
    		var selectedPhoto = -1;
    		
			var map;
			var geocoder;
			var markers = new Array();
        	var numMarkers = "<?php echo count($media_arr) ?>";
        	var latValues = eval(<?php echo json_encode($lats) ?>);
        	var lngValues = eval(<?php echo json_encode($lngs) ?>);
        	var photoDates = eval(<?php echo str_replace($date_delims, '.', json_encode($dates)) ?>);
        	var audioFiles = eval(<?php echo json_encode($audios) ?>);
        	var orientations = eval(<?php echo json_encode($orientations) ?>);
        	
        	var blueIcon = new GIcon(G_DEFAULT_ICON);
			blueIcon.image = "http://www.google.com/mapfiles/marker_purple.png";
			/*
			blueIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        	blueIcon.iconSize = new GSize(20, 34);
			blueIcon.shadowSize = new GSize(37, 34);
        	blueIcon.iconAnchor = new GPoint(9, 34);
        	blueIcon.infoWindowAnchor = new GPoint(9, 2);
        	*/
			var blueMarkerOptions = { icon:blueIcon };
			
			var activeMarker = null;
			var activeMarkerId;
			        	
        	var months=new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

			function createMarker(point, id){
			    var marker = new GMarker(point);
			    markers[id] = marker;
          		map.addOverlay(marker);
          		GEvent.addListener(marker, "click", function() {
          			var selector = "#photo" + id;
  					$(selector).click();		

				});
			}

    		function initialize() {
      			if (GBrowserIsCompatible()) {
        			map = new GMap2(document.getElementById("map_container"));
        			map.setUIToDefault();

					var latlngBounds = new GLatLngBounds();

        			for (var i = 0; i < numMarkers ; i++) {
        				if(latValues[i] != null && lngValues[i] != null){
        					//alert(latValues[i] + "," + lngValues[i]);
          					var point = new GLatLng(latValues[i], lngValues[i]);
          					latlngBounds.extend(point);
          					createMarker(point, i);
          				}
        			}
        			
        			map.setCenter( latlngBounds.getCenter( ), map.getBoundsZoomLevel( latlngBounds ) );
					geocoder = new GClientGeocoder();
      			}
    		}

    	</script>
    	
    	<script>

			/*
			function isLandscapeOrientation(){
				var landscape = true;
    			if($("#hidden_image").outerWidth() < $("#hidden_image").outerHeight()){
    				landscape = false;
    			}
    			return landscape;			
			}
			*/
			
			function updateDate(id){
				var date = photoDates[id];
    			var dateParts = date.split(".");
    			
    			var d = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], dateParts[3], dateParts[4], dateParts[5]);
    			var hours = d.getHours();
    			var meridiem = "am";
				if(hours >= 12){
    				meridiem = "pm";
    				hours = hours - 12;
    			}
				if(hours == 0) hours = 12;
				
    			var minutes = d.getMinutes();
    			if(minutes < 10){
    				minutes = "0" + minutes;
				}
    				
				$("#date").html(hours + ":" + minutes + " " + meridiem + " " + months[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear());
			}
			
			function centerMap(id){
			    if(latValues[id] != null && lngValues[id] != null){
    				map.setCenter(new GLatLng(latValues[id], lngValues[id]));
    			}
			}
			
			function setAudioFile(id){
			    $("li.audio").attr("style", "display:none");
			    
			    var file = audioFiles[id];
			    
			    if(file != null){
			    	var audioSelector = "#audio" + id;
			    	$(audioSelector).parent().attr("style", "display: block");
			    }
			}
			
			function setPhotoOrientation(id) {
				var orientation = orientations[id];
				$("#overlay_pic").attr("style", "-webkit-transform: rotate(" + orientation + "deg); -moz-transform: rotate(" + orientation + "deg);");
				
				if(orientation == 90 || orientation == 270){
					if(id == 0){
						$("#overlay_pic").css("margin-left", "135px");
					} else {
						$("#overlay_pic").css("margin-left", "105px");
					}
					$("#overlay_pic").css("margin-right", "105px");
					$("#overlay_pic").css("margin-top", "55px");
					$("#overlay_pic").css("margin-bottom", "55px");
					$("#overlay_pic").css("width", "380px");
					$("#overlay_pic").css("height", "285px");
				} else {
					if(id == 0){
						$("#overlay_pic").css("margin-left", "40px");
					} else {
						$("#overlay_pic").css("margin-left", "10px");
					}
					$("#overlay_pic").css("margin-right", "10px");
					$("#overlay_pic").css("margin-top", "10px");
					$("#overlay_pic").css("margin-bottom", "5px");
					$("#overlay_pic").css("width", "570px");
					$("#overlay_pic").css("height", "380px");
				}
				

			}
			
			function removeActiveMarker(){
				if(activeMarker != null){
					map.removeOverlay(activeMarker);
					var replacement = createMarker(activeMarker.getLatLng(), activeMarkerId);
					activeMarker = null;
					activeMarkerId = null;
				}
			}
			
			function updateMapMarkers(id){
					
					var point = new GLatLng(latValues[id], lngValues[id]);
					removeActiveMarker();
			
					var marker = markers[id];
				  	if(marker){
				  	
				  		map.removeOverlay(marker);
  					
  						//create new marker
						marker = new GMarker(point, blueMarkerOptions);
						map.addOverlay(marker);

  						//add to array
  						markers[id] = marker;
  						
  						activeMarker = marker;
  						activeMarkerId = id;
				  	}

			}
			
			function updatePhotoSelectionProperties(id){
					centerMap(id);    				
    				updateDate(id);
    				setAudioFile(id);
    				setPhotoOrientation(id);
    				updateMapMarkers(id);
			}
			
				$(function() {
					$("#main img[rel]").overlay({
						effect: 'apple',
						left: '-5px'
					});
				});

			jQuery(document).ready(function(){
				$("div.apple_overlay .close").click(function(){
					removeActiveMarker();
				});
			
    			$("#main img[rel]").click(function(){
    				$("#overlay_pic").attr("src", $(this).attr("src"));
    				$("#hidden_image").attr("src", $(this).attr("src"));
    				
    				//var landscape = isLandscapeOrientation();
    				
    				var id = $(this).attr("id").substring(5);
    				selectedPhoto = parseInt(id);
    				
    				//set display buttons
    				if(selectedPhoto <= 0){
    					$("#prev_pic").css("display", "none");
    					$("#overlay_pic").css("margin-left", "40px");
    				} else {
    				    $("#prev_pic").css("display", "block");
    					$("#overlay_pic").css("margin-left", "10px");
    				}
    				
    				if(selectedPhoto >= numMarkers - 1){
    					$("#next_pic").css("display", "none");
    				} else {
    				    $("#next_pic").css("display", "block");
    				}
    				
    				updatePhotoSelectionProperties(selectedPhoto);
    			});
    			
    			$("#prev_pic").click(function(){
    				//alert(selectedPhoto);
    				if(selectedPhoto > 0){
    				    selectedPhoto = parseInt(selectedPhoto) - 1;
    					$("#overlay_pic").attr("src", $("#photo" + selectedPhoto).attr("src"));
    				}
    				if(selectedPhoto <= 0){
    					$(this).css("display", "none");
    					$("#overlay_pic").css("margin-left", "40px");
    				}
    				$("#next_pic").css("display", "block");
    				
    				updatePhotoSelectionProperties(selectedPhoto);
    			});
    			
    			
    			$("#next_pic").click(function(){
    				//alert(selectedPhoto);
    				if(selectedPhoto < numMarkers - 1){
    				    selectedPhoto = parseInt(selectedPhoto) + 1;
    					$("#overlay_pic").attr("src", $("#photo" + selectedPhoto).attr("src"));
    				}
    				if(selectedPhoto >= numMarkers - 1){
    					$(this).css("display", "none");
    				}
    				$("#prev_pic").css("display", "block");
    				$("#overlay_pic").css("margin-left", "10px");
    				
    				updatePhotoSelectionProperties(selectedPhoto);
    				
    			});
    			
    			$("ul.thumb li").hover(function() {
					$(this).css({'z-index' : '10'}); /*Add a higher z-index value so this image stays on top*/ 
					$(this).find('img').addClass("hover").stop() /* Add class of "hover", then stop animation queue buildup*/
						.animate({
							marginTop: '-60px', /* The next 4 lines will vertically align this image */ 
							marginLeft: '-60px',
							top: '50%',
							left: '50%',
							width: '120px', /* Set new width */
							height: '120px', /* Set new height */
						}, 50); /* this value of "200" is the speed of how fast/slow this hover animates */

				} , function() {
					$(this).css({'z-index' : '0'}); /* Set z-index back to 0 */
					$(this).find('img').removeClass("hover").stop()  /* Remove the "hover" class , then stop animation queue buildup*/
						.animate({
							marginTop: '0', /* Set alignment back to default */
							marginLeft: '0',
							top: '0',
							left: '0',
							width: '110px', /* Set width back to default */
							height: '110px' /* Set height back to default */
					}, 50);
				});
    			
    			
			});



		</script>
		
	</head>

	<body onload="initialize()" onunload="GUnload()">
		<div id="wrap">
			<div id="banner">
				<div id="logo"><img src="logo.png"/></div>
				<div id="subtitle">A Puh-puh-puh-puppy Production</div>
			</div>
			<div id="main">
				<div style="height:5px"></div>
      
      				<?php
      				
      					if(count($media_arr) > 0){
      						$first_date = $media_arr[0]->time_captured();
							$first_date_display = $months[$first_date->month()] . " " . $first_date->day() . ", " . $first_date->year();
      						echo "<div class='list_date'>$first_date_display</div>";
      						echo "<ul class='items thumb'>";

      						$prev_time = null;
      						$list_open = true;

      						for($j = 0; $j < count($media_arr); $j++){
      							$m = $media_arr[$j];

      							$time = $m->time_captured();
      							
      							$orientation = $m->photo_orientation();

								if($prev_time != null){
									if(differentDay($prev_time, $time)){
										$curr_date = $media_arr[$j]->time_captured();
										$curr_date_display = $months[$curr_date->month()] . " " . $curr_date->day() . ", " . $curr_date->year();
										echo "</ul><div class='list_date'>$curr_date_display</div><ul class='items thumb'>";
									}
								}
      							$src = $m->photo_filename();      							      										   $thumb = str_replace("photo", "thumb", $src);
							echo "<li>";
      							echo "<img id='photo$j' src='../$thumb' rel='#big_pic' alt='' style='-webkit-transform: rotate(".$orientation."deg); -moz-transform: rotate(".$orientation."deg);'/>";
      							$audio = $m->audio_filename();
      							if($audio != null) {
      								$audioPath = "../$audio";
      								exec("/usr/bin/ffmpeg -i \"$audioPath\" 2>&1", $out);
									$search='/Duration: 00:0(.*)\..*start/';
									preg_match($search, $out[11], $matches, PREG_OFFSET_CAPTURE);
									$duration = $matches[1][0];
      								echo "<p><a href='$audioPath' class='sm2_button'>Play Audio</a><span style='margin-left:5px'>$duration</span></p>";
      								$out = null;
      							}
      							echo "</li>";
      							$prev_time = $time;
      						}

      					}
      				
      				?>
      				
      				
      
  				</ul>
				
			</div>
	
			<div id="sidebar">
				<div id="outer_map_holder">
					<div id="background">
						<img class="stretch" src="rounded-box.png" />
					</div>
					<div id="map_container" >
				
					</div>
				</div>
			</div>
		</div>
		
		<div class="apple_overlay" id="big_pic">
			<img id="prev_pic" src="button-left.png" class="arrow"/>
			<img id="overlay_pic" src=""/>
			<img id="next_pic" src="button-right.png" class="arrow"/>

			<div id="annotation">
		
				<ul class="playlist" style="margin-bottom:30px">
					
					<?php
						
						for($j = 0; $j < count($media_arr); $j++){
      						$m = $media_arr[$j];

      						$audio = $m->audio_filename();

      						if($audio != null) {
      							$audioPath = "../$audio";
      							echo "<li class='audio' style='display:none'><a id='audio$j' href='$audioPath'>Play Audio </a></li>";
      						}
      					}
					
					?>
				</ul>
				
			</div>
			<div id="date">
			</div>
		</div>
	
	</body>

</html>
